import React, { useState } from "react";
import './index.less';
import { Input, Button, message } from 'antd';
import { connect } from "react-redux";
import { addDevItemAction, reviseDevItemAction } from '@redux/actions';
import { useNavigate, useSearchParams } from "react-router-dom";

const { TextArea } = Input;

const DevelopmentEdit = (props) => {

  const navigate = useNavigate();
  const [params] = useSearchParams();
  const { addDevItemAction, reviseDevItemAction } = props;

  const [content, setContent] = useState(params.get('content') ? decodeURIComponent(params.get('content')) : '');
  const [contriId, setContriId] = useState(params.get('contriId') ? JSON.parse(params.get('contriId')).join(';') : '');
  const [devProg, setDevProg] = useState(params.get('devProg') ? params.get('devProg') : '');

  const submitPre = () => {
    if (!content.trim()) {
      message.error('内容不能为空');
      return;
    }
    if (!contriId.trim()) {
      message.error('贡献人员不能为空');
      return;
    }
    const contri = contriId.trim();
    let arr = [];
    if (contri.includes(';')) {
      arr = contri.split(';').map(item => parseInt(item));
    } else {
      arr.push(parseInt(contri));
    }
    if (!devProg) {
      message.error('研发进度不能为空');
      return;
    }
    if (isNaN(devProg)) {
      message.error('研发进度必须是数值');
      return;
    }
    if (devProg < 0 || devProg > 100) {
      message.error('研发进度必须是0-100的整数');
      return;
    }
    params.get('id')
    ? reviseDevItemAction(params.get('id'), content, arr, parseInt(devProg), navigate)
    : addDevItemAction(content, arr, parseInt(devProg), navigate);
  }

  return <div className="previousfonc_edit">
    <TextArea placeholder="请输入往期功能内容" className="content"
      value={content}
      onChange = {e => {setContent(e.target.value)}}
    />
    <Input placeholder="请输入贡献人员id，以分号分隔" className="contriId"
      value={contriId}
      onChange={e => {setContriId(e.target.value)}}
    /> 
    <Input type="number" placeholder="请输入研发进度0-100之间的整数" className="devProg"
      value={devProg}
      onChange={(e) => {setDevProg(e.target.value)}}
    />
    <Button className="submit" onClick={submitPre}>提交</Button>
  </div>
}

export default connect(
  state => state,
  { addDevItemAction, reviseDevItemAction }
)(DevelopmentEdit);